﻿using LibNet.Http;
using LibPlug.Interface;
using LibPlug.Model;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json.Linq;
using WMPLib;
using System.Threading;

namespace LibDianGe
{
    /// <summary>
    /// 弹幕点歌插件
    /// </summary>
    [PluginsInfo("弹幕点歌插件","Zony","可以自定义弹幕点歌格式进行点歌的插件~",1000)]
    public class LibDianGe : IPlug
    {
        private Queue<string> m_songList = new Queue<string>();
        private NetUtils m_netUtils = new NetUtils();
        private WindowsMediaPlayer m_wmp;

        public PluginsInfoAttribute Info { get; set; }

        public bool ReceiveMessage(DanMuMessageModel model)
        {
            dataAssmblerMethod(model);
            return true;
        }

        public bool Init(object parameters)
        {
            if (m_wmp == null)
            {
                m_wmp = new WindowsMediaPlayer();
            }
            m_wmp.PlayStateChange += M_wmp_PlayStateChange;
            return true;
        }

        private void M_wmp_PlayStateChange(int NewState)
        {
            WMPPlayState _state = (WMPPlayState)NewState;
            if (_state == WMPPlayState.wmppsMediaEnded)
            {
                playMusic();
            }
        }

        /// <summary>
        /// 弹幕消息解析
        /// </summary>
        private void dataAssmblerMethod(DanMuMessageModel msg)
        {
            // 暂定格式，“点歌-歌名”
            if(msg.Content.Contains("点歌"))
            {
                string[] _result = msg.Content.TrimEnd('-').Split('-');
                if (_result.Length > 1)
                {
                    string _musicName = _result[1];
                    getMusicUrl(_musicName);
                }
            }else if(msg.Content.Contains("歌单")) // 歌单-XXXXX
            {
                string[] _result = msg.Content.TrimEnd('-').Split('-');
                if(_result.Length > 1)
                {
                    // 网易云歌单
                }
            }
        }

        /// <summary>
        /// 获得歌曲的URL
        /// </summary>
        private void getMusicUrl(string musicName)
        {
            string _reqUrl = @"http://music.163.com/api/search/get/web?csrf_token=";
            string _key = m_netUtils.URL_Encoding(musicName, Encoding.UTF8);
            string _reqData = "&s=" + _key + "&type=1&offset=0&total=true&limit=5";

            string _json = m_netUtils.HttpPost(_reqUrl,"http://music.163.com",Encoding.UTF8,_reqData);
            if(!string.IsNullOrEmpty(_json))
            {
                string _sid = getSID(_json);
                if (!string.IsNullOrEmpty(_sid))
                {
                    string songURL = "http://music.163.com/api/song/detail/?id=" + _sid + "&ids=%5B" + _sid + "%5D";
                    string _result = m_netUtils.HttpGet(songURL, "", Encoding.UTF8);
                    string _url = getUrl(_result);
                    lock(m_songList)
                    {
                        m_songList.Enqueue(_url);
                        playMusic();// mdzz
                    }
                }
            }
        }

        /// <summary>
        /// 获得歌曲SID
        /// </summary>
        /// <returns></returns>
        private string getSID(string json)
        {
            JObject _jsonSid = JObject.Parse(json);
            if (!json.Contains("result")) return null;
            if (_jsonSid["result"]["songCount"].Value<int>() == 0)
            {
                return null;
            }

            JArray _jarraySID = (JArray)_jsonSid["result"]["songs"];
            return _jarraySID[0]["id"].ToString();
        }

        /// <summary>
        /// 解析URL
        /// </summary>
        private string getUrl(string json)
        {
            JArray _songs = (JArray)JObject.Parse(json)["songs"];
            return _songs[0]["mp3Url"].ToString().Replace("m2","p2");
        }

        private void playMusic()
        {
            lock(m_songList)
            {
                if(m_songList.Count > 0 && m_wmp.playState != WMPPlayState.wmppsPlaying)
                {
                    string _url = m_songList.Dequeue();
                    m_wmp.URL = _url;
                }
            }
        }
    }
}
